package debug

import (
	"fmt"
	"net"
	"net/http"
	"net/http/pprof"
)

var pprofListener net.Listener
var pprofServer *http.Server
var pprofMux = http.NewServeMux()

// 开启pprof http server
func StartPprofServer(ip string, port int) (addr string, err error) {
	if pprofListener != nil {
		return "", fmt.Errorf("pprof http server has started")
	}

	pprofListener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", ip, port))
	if err != nil {
		return "", fmt.Errorf("start pprof http server fail, %s", err)
	}

	addr = pprofListener.Addr().String()

	// 开启pprof server
	pprofMux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
	pprofMux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
	pprofMux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
	pprofMux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
	pprofMux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
	pprofServer = &http.Server{
		Addr:    ip,
		Handler: pprofMux,
	}

	go pprofServer.Serve(pprofListener)

	return
}

// 开启pprof http server
func StartPprofServer2(addr string) (string, error) {
	if pprofListener != nil {
		return "", fmt.Errorf("pprof http server has started")
	}

	var err error
	pprofListener, err = net.Listen("tcp", addr)
	if err != nil {
		return "", fmt.Errorf("start pprof http server fail, %s", err)
	}

	// 开启pprof server
	pprofMux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
	pprofMux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
	pprofMux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
	pprofMux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
	pprofMux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
	pprofServer = &http.Server{
		Addr:    addr,
		Handler: pprofMux,
	}

	go pprofServer.Serve(pprofListener)

	return pprofListener.Addr().String(), nil
}

// 关闭pprof http server
func StopPprofServer() {
	pprofServer.Close()
	pprofListener.Close()
	pprofListener = nil
}

// 注册调试指令
func RegisterCommand(pattern string, handler http.HandlerFunc) {
	pprofMux.Handle(pattern, handler)
}
